using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

[ExecuteAlways]
[RequireComponent(typeof(SpriteRenderer))]
public class SimpleFrameAnimation : MonoBehaviour
{
    public enum FrameAnimationEvent
    {
        Start, Stop, Pause, End
    }

    [SerializeField] private List<Sprite> frames;
    [SerializeField] private float duration;
    [SerializeField] private bool playOnAwake;
    [SerializeField] private bool loop;
    public event Action<FrameAnimationEvent> onFrameAnimationEvent;

    private int frameIndex;
    private bool running;
    private float accmulate;
    private SpriteRenderer spriteRenderer;

    private void Awake()
    {
        TryGetComponent<SpriteRenderer>(out spriteRenderer);
        if (playOnAwake) Play();
    }

    private void Update()
    {
        if (!running) return;

        accmulate += Time.deltaTime;
        while(accmulate >= duration)
        {
            if (duration <= 0) break;

            frameIndex ++;
            frameIndex %= frames.Count;
            accmulate -= duration;
            spriteRenderer.sprite = frames[frameIndex];

            if (frameIndex == frames.Count - 1)
                onFrameAnimationEvent?.Invoke(FrameAnimationEvent.End);
                
            if (!loop) Stop();
        }
    }

    public void Play()
    {
        running = true;
        frameIndex = 0;
        accmulate = 0;
        spriteRenderer.sprite = frames[frameIndex];
        onFrameAnimationEvent?.Invoke(FrameAnimationEvent.Start);
    }

    public void Pause()
    {
        running = false;
        onFrameAnimationEvent?.Invoke(FrameAnimationEvent.Pause);
    }

    public void Stop()
    {
        running = false;
        frameIndex = 0;
        accmulate = 0;
        onFrameAnimationEvent?.Invoke(FrameAnimationEvent.Stop);
    }
}
